// /pages/team-list/team-list.js
import {
    getTeamList,
    setAdmin,
    delMember,
    getNewTeamList,
    getSeatListInfo,
    coSeatInfo,
    setSeat,
} from '../../api/app.js'
import user from '../../utils/user.js'
import {
    toast,
    confirm,
} from '../../utils/util.js'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabIndex: 0,
        teamList: [],
        isSelect: false,
        isRadio: false,
        selects: [],
        moreList: [],
        moreStatus: false,
        moreTop: 0,
        myId: '',
        isAdmin: false,
        isSuperAdmin: false,
        leadList: [],
        creatorId: '',
        searchText: '',
        newTeamNum: '',
        curTab: '',
        tabList: [
            {
                name: '全部成员',
                value: ''
            },
            {
                name: '已分配',
                value: 0
            },
            {
                name: '未分配',
                value: 1
            }
        ],
        seatInfoList: [],
        userName: '',
        pageInfo: {
            pageNum: 1,
            pageSize: 10
        },
        timer: null,
        isSelectAll: false,
        isClickButton: false,
        seatInfo: {},
        curSelecdtedValue: 0,
        hasNextPage: true,
        cachedSeatInfo: [],
        cachedAllSeatInfo: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        user.waitLogin().then(res => {
            console.log(options, '参数路径')
            if (options.leadList) {
                this.setData({
                    leadList: options.leadList, // 原本选中的成员列表
                    creatorId: options.creatorId // 创建者ID，禁止取消选择
                })
            }
            // 是否开启选择成员模式
            if (options.select) {
                this.setData({
                    isSelect: options.select,
                })
            }
            // 选择成员单选或多选，默认多选
            if (options.type) {
                this.setData({
                    isRadio: options.type === 'radio'
                })
            }
            this.setData({
                myId: user.userId,
                isAdmin: user.isAdmin,
                isSuperAdmin: user.isSuperAdmin
            })
            console.log(this.data.isAdmin, 'isAdmin')
        })

    },
    onShow() {
        // 获取成员列表
        user.waitLogin().then(() => {
            if (this.data.isAdmin) {
                this.getNewTeamNum()
            }
            getTeamList({
                companyId: user.companyId,
                userName: this.data.searchText
            }).then(res => {
                console.log(res,'dhjfhiubghjbfg');
                const temporaryArr = []
                const selects = this.data.selects
                // 根据leadlist还原已经选择的
                if (this.data.leadList.length >= 1) {
                    const arr = this.data.leadList.split(',')
                    // 逐个对比将已经勾选的标记
                    res.map(item => {
                        arr.forEach(ite => {
                            if (item.userId == ite) {
                                item.controller = true
                                selects.push({
                                    name: item.userName,
                                    id: item.userId,
                                    position: item.position,
                                    phone: item.phone,
                                })
                            }
                        })
                        return item
                    })
                    // 排序，按创建者、选中的、 未选中的依次排序
                    temporaryArr.push(...res.filter(item => item.userId == this.data.creatorId))
                    temporaryArr.push(...res.filter(item => item.controller && (item.userId != this.data.creatorId)))
                    temporaryArr.push(...res.filter(item => !item.controller))
                }
                console.log(selects)
                this.setData({
                    teamList: temporaryArr.length >= 1 ? temporaryArr : res,
                    selects
                })
            })

            this.getSeatManagementData()
            this.coSeatInfo()
        })

    },
    // 跳转到新界面邀请成员
    addTeamList() {
        wx.navigateTo({
            url: '/packagePay/pages/master-invitation-qrcode/master-invitation-qrcode'
        })
    },
    // 选择员工
    onSelect(event) {
        let selects = this.data.selects
        const data = event.currentTarget.dataset
        // 创建者不可被取消勾选
        if (data.id == this.data.creatorId) {
            app.toast('创建者不可被取消勾选')
            return
        }
        // 如果是单选状态 覆盖选中
        if (this.data.isRadio) {
            selects = [{
                name: data.name,
                id: data.id,
                position: data.position,
                phone: data.phone,
            }]
        }
        // 如果是多选状态则追加选中
        else {
            let index = -1
            for (const i in selects) {
                if (selects[i].id === data.id) {
                    index = i
                }
            }
            if (index === -1) {
                selects.push({
                    name: data.name,
                    id: data.id,
                    position: data.position,
                    phone: data.phone,
                })
            } else {
                selects.splice(index, 1)
            }
        }
        this.setData({
            selects
        })
        console.log(this.data.selects)
    },
    // 完成选择
    onSubmitSelect() {
        // 获取所有页面实例
        const pages = getCurrentPages()
        // 获取上一个页面实例
        const page = pages[pages.length - 2]
        // 调用上一个页面的实例，将选择的员工传回
        page[this.data.isSelect](this.data.selects)
        // 回到上一个界面
        wx.navigateBack()
    },
    // 显示更多
    showMore(event) {
        console.log(event)
        // 根据不同情况定制更多弹窗的内容和位置
        const list = []
        // 如果是老项目，不允许删除员工
        if (user.isSuperAdmin || (user.isAdmin && !event.currentTarget.dataset.admin)) {
            list.push({
                text: '删除',
                key: event.currentTarget.dataset.id,
                icon: '',
                bind: 'delete'
            })
        }
        // 当前使用者为超级管理员时允许设置管理员
        // user.isSuperAdmin && !event.currentTarget.dataset.admin
        if (user.isSuperAdmin) {
            list.push({
                text: '设置',
                key: event.currentTarget.dataset.id,
                icon: '',
                bind: 'setAdmin'
            })
        }
        // else if (user.isSuperAdmin && event.currentTarget.dataset.admin) {
        //     list.push({
        //         text: '取消管理员',
        //         key: event.currentTarget.dataset.id,
        //         icon: '',
        //         bind: 'cancelAdmin'
        //     })
        // }
        this.setData({
            'moreList': list
        })
        this.setData({
            moreTop: event.touches[0].clientY + 6, // 根据触摸的轴选定更多弹窗的位置
            moreStatus: true
        })
    },
    // 隐藏更多选项
    hideMore() {
        this.setData({
            moreStatus: false
        })
    },
    // 去设置页面
    goSetAdmin(event) {
        console.log('去设置页面', event)
        const { userid } = event.currentTarget.dataset
        console.log(userid, user.userId, 'userId')
        console.log(userid !== user.userId)
        const userInfo = this.data.teamList.filter(item => {
            if (item.userId == event.currentTarget.dataset.id) {
                return item
            }
        })
        console.log(user.isSuperAdmin && user.isAdmin && (userid !== user.userId))
        // 是超级管理员 但是不可以进自己的详情页
        if (user.isSuperAdmin && user.isAdmin && (userid === user.userId)) {
            return
        }
        // 是管理员 只能进普通用户的信息修改页面
        if (user.isSuperAdmin || (user.isAdmin && !event.currentTarget.dataset.admin)) {
            wx.navigateTo({
                url: '/pages/edit-team/edit-team?id=' + event.currentTarget.dataset.id + '&isAdmin=' + userInfo[0].isAdmin + '&isPcAdmin=' + userInfo[0].isPcAdmin + '&name=' + userInfo[0].userName + '&position=' + userInfo[0].position + '&phone=' + userInfo[0].phone,
            })
            return
        }
        // 是超级管理员  可以进所有用户的信息修改页面
        if (user.isSuperAdmin && user.isAdmin) {
            console.log(userInfo[0], '这里？？？')
            wx.navigateTo({
                url: '/pages/edit-team/edit-team?id=' + event.currentTarget.dataset.id + '&isAdmin=' + userInfo[0].isAdmin + '&isPcAdmin=' + userInfo[0].isPcAdmin + '&name=' + userInfo[0].userName + '&position=' + userInfo[0].position + '&phone=' + userInfo[0].phone,
            })
            return
        }
        // url: '/packageContract/pages/sign-poster/sign-poster?servecompany=' + this.data.serveCompanyName + '&id=' + this.data.projectId
        // app.confirm('是否设置为管理员？').then(() => {
        //     setAdmin({
        //         memberId: event.detail,
        //         type: 1
        //     }).then(() => {
        //         app.toast('设置成功！', 'success')
        //         this.onShow()
        //     })
        // }) 
    },
    // 取消管理员权限
    cancelAdmin(event) {
        app.confirm('是否取消为管理员权限？').then(() => {
            setAdmin({
                memberId: event.detail,
                type: 2
            }).then(() => {
                app.toast('取消权限成功！', 'success')
                this.onShow()
            })
        })
    },
    // 删除员工
    deleteT(event) {
        app.confirm('是否删除该员工？').then(() => {
            delMember({
                memberId: event.detail,
            }).then(() => {
                app.toast('删除成功！', 'success')
                this.onShow()
            })
        })
    },
    // 搜索
    searchWorker() {
        console.log(this.data.searchText, 'searchText')
        this.setData({
            seatInfoList: []
        })
        this.searchSeatInfoList()
    },
    // 去新团队成员审核
    goTeamAuditingList() {
        wx.navigateTo({
            url: '/pages/team-auditing-list/team-auditing-list',
        })
    },
    async getNewTeamNum() {
        const result = await getNewTeamList({
            companyId: user.companyId
        })
        this.setData({
            newTeamNum: result.pendingReview
        })
        console.log(result, 'resultresult')
    },
    onTab(e) {
        console.log(e);
        this.setData({
            tabIndex: e.detail
        })
    },
    changeTab(e) {
        const curItem = e.target.dataset.item
        this.handleCancle()
        this.setData({
            curTab: curItem.value,
            ['pageInfo.pageNum']: 1,
            ['pageInfo.pageSize']: 10,
            isClickButton: false
        })
        this.getSeatManagementData()
    },
    getSeatManagementData() {
        getSeatListInfo({
            status: this.data.curTab,
            pageNum: this.data.pageInfo.pageNum,
            pageSize: this.data.pageInfo.pageSize,
            // userName: this.data.userName
            userName: this.data.searchText
        }).then(res => {
            if (res?.list?.length) {
                res.list.forEach(i => i.isSelected = i.isSeatAdmin === 1 || this.data.isSelectAll)
            }
            if (this.data.pageInfo.pageNum !== 1) {
                this.setData({
                    seatInfoList: this.data.seatInfoList.concat(res.list || [])
                })
            } else {
                this.setData({
                    seatInfoList: res.list || []
                })
            }

            // tab为全部时，缓存所有人员，未分配时需要带上所有席位管理员的userId
            if (this.data.curTab === '' && !this.data.userName) {
                const seatIdList = this.data.seatInfoList.filter(i => i.isSeatAdmin) || []
                const seatIds = seatIdList.map(i => i.userId) || []
                this.setData({
                    cachedSeatInfo: seatIds,
                    cachedAllSeatInfo: seatIds
                })
            }
            const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
            this.setData({
                isSelectAll: selectedList.length === res.list.length,
                curSelecdtedValue: selectedList.length,
                hasNextPage: res.hasNextPage
            })
        })
    },
    // 获取席位列表
    searchSeatInfoList() {
        if (this.data.timer) clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.setData({
                ['pageInfo.pageNum']: 1,
                ['pageInfo.pageSize']: 10,
            })
            this.getSeatManagementData()
        }, 300);
    },
    // 获取席位信息
    coSeatInfo() {
        coSeatInfo({}).then(res => {
            this.setData({
                seatInfo: res || {}
            })
        })
    },
    changeSelect(e) {
        const dataset = e.currentTarget.dataset
        if (dataset.isapprove) {  // 在审批流
            if (dataset.isseatadmin) {
                confirm(`该员工为发薪项目审批人，需超级管理员取消其审批人身份后，才可取消席位管理员审批`, {
                    confirmText: user.isSuperAdmin ? '进审批流' : '知道了',
                    showCancel: user.isSuperAdmin,
                    confirmColor: '#00D679'
                })
                    .then(res => {
                        if (user.isSuperAdmin) {
                            wx.navigateTo({
                                url: '/pages/flow/index/index'
                            })
                        } else {
                            this.setCheckData(dataset, true)
                            // this.data.seatInfoList[dataset.index].isSelected = true
                            // this.setData({
                            //     seatInfoList: this.data.seatInfoList
                            // })
                            // const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
                            // this.setData({
                            //     isSelectAll: selectedList.length === this.data.seatInfoList.length,
                            //     curSelecdtedValue: selectedList.length
                            // })
                        }
                    }).catch(err => {
                        this.setCheckData(dataset, true)
                        // this.data.seatInfoList[dataset.index].isSelected = true
                        // this.setData({
                        //     seatInfoList: this.data.seatInfoList
                        // })
                        // const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
                        // this.setData({
                        //     isSelectAll: selectedList.length === this.data.seatInfoList.length,
                        //     curSelecdtedValue: selectedList.length
                        // })

                    })
            } else {
                this.setCheckData(dataset, !dataset.isselected)
                // this.data.seatInfoList[dataset.index].isSelected = !dataset.isselected
                // this.setData({
                //     seatInfoList: this.data.seatInfoList
                // })
                // const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
                // this.setData({
                //     isSelectAll: selectedList.length === this.data.seatInfoList.length,
                //     curSelecdtedValue: selectedList.length
                // })
            }
        } else {  // 不在审批流
            this.setCheckData(dataset, !dataset.isselected)
            // this.data.seatInfoList[dataset.index].isSelected = !dataset.isselected
            // this.setData({
            //     seatInfoList: this.data.seatInfoList
            // })
            // const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
            // this.setData({
            //     isSelectAll: selectedList.length === this.data.seatInfoList.length,
            //     curSelecdtedValue: selectedList.length
            // })
        }
    },
    setCheckData(dataset, bl) {
        this.data.seatInfoList[dataset.index].isSelected = bl
        console.log(1111, dataset, bl);

        if (!bl) {
            console.log(2222, this.data.cachedSeatInfo);
            const index = this.data.cachedSeatInfo.findIndex(i=> i === dataset.userid)
            if (index!==-1) {
                this.data.cachedSeatInfo.splice(index, 1)
                this.setData({
                    cachedSeatInfo: this.data.cachedSeatInfo
                })
            }
        }

        this.setData({
            seatInfoList: this.data.seatInfoList
        })
        const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
        this.setData({
            isSelectAll: selectedList.length === this.data.seatInfoList.length,
            curSelecdtedValue: selectedList.length
        })
    },
    changeSelectAll(e) {
        this.setData({
            isSelectAll: !e.target.dataset.isselectall
        })
        this.data.seatInfoList.forEach(i => {
            i.isSelected = this.data.isSelectAll
        })
        const selectedList = this.data.seatInfoList.filter(i => i.isSelected)
        this.setData({
            seatInfoList: this.data.seatInfoList,
            curSelecdtedValue: selectedList.length
        })
    },
    changeClickButton() {
        this.setData({
            isClickButton: true
        })
    },
    handleCancle() {
        this.data.seatInfoList.forEach(i => i.isSelected = i.isSeatAdmin === 1)
        this.setData({
            isClickButton: false,
            isSelectAll: false,
            seatInfoList: this.data.seatInfoList,
            cachedSeatInfo: this.data.cachedAllSeatInfo
        })
    },
    toBuySeat() {
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-recharge-bullet/insurance-recharge-bullet'
        })
    },
    handleConfirm() {
        const list = this.data.seatInfoList.filter(i => i.isSelected)
        let mapList = list.map(i => i.userId)


        mapList = mapList.concat(this.data.cachedSeatInfo)
        mapList = [...new Set(mapList)]

        if (!mapList?.length) {
            confirm('取消发薪席位分配后，用户将无法正常使用相应功能，是否继续？', {
                confirmColor: '#00D679'
            }).then(res => {
                this.doSetSeat(mapList)
            }).catch(err => {
                console.log(22, err);
            })
            return
        }
        if (mapList.length > this.data.seatInfo.hasSeat) {
            confirm('已达到席位上限，需购买席位后再次分配', {
                confirmText: '去购买',
                confirmColor: '#00D679'
            }).then(res => {
                this.toBuySeat()
            }).catch(err => {
                console.log(22, err);
            })
            return
        }
        this.doSetSeat(mapList)
    },
    doSetSeat(mapList) {
        setSeat({
            isAllchecked: this.data.isSelectAll,
            userIds: mapList,
            companyId: user.companyId
        }).then(res => {
            if (res?.data?.code === 500) {
                confirm(`${res?.data?.msg}为发薪项目审批人，需超级管理员取消其审批人身份后，才可取消席位管理员审批`, {
                    confirmText: user.isSuperAdmin ? '进审批流' : '知道了',
                    showCancel: user.isSuperAdmin,
                    confirmColor: '#00D679'
                })
                    .then(res => {
                        if (user.isSuperAdmin) {
                            wx.navigateTo({
                                url: '/pages/flow/index/index'
                            })
                        }
                    }).catch(err => {
                        console.log(22, err);
                    })
            } else {
                toast('保存成功', 'success')

                this.setData({
                    isClickButton: false,
                    cachedSeatInfo: mapList
                })
                this.coSeatInfo()
                this.searchSeatInfoList()
            }
        })
    },
    onReachBottom() {
        if (this.data.hasNextPage) {
            this.data.pageInfo.pageNum++
            this.getSeatManagementData()
        }
    },
})